package main

import (
	"bytes"
	"fmt"
	"io"
	"net"
	"net/url"
	"strings"
)

func main() {
	listen, err := net.Listen("tcp", ":9001")
	if err != nil {
		panic(err)
	}

	for {
		conn, err := listen.Accept()
		if err != nil {
			panic(err)
		}

		go handler(conn)
	}
}

func handler(conn net.Conn)  {
	if conn == nil {
		return
	}

	defer func() {
		_ = conn.Close()
	}()

	var bs [2048]byte

	n, err := conn.Read(bs[:])
	if err != nil {
		panic(err)
	}

	var method, host, address string
	_, _ = fmt.Sscanf(string(bs[:bytes.IndexByte(bs[:], '\n')]), "%s%s", &method, &host)
	if strings.HasPrefix(host, "192.168") {
		return
	}

	fmt.Println(string(bs[:n]))
	hostPortURL, err := url.Parse(host)
	if err != nil {
		panic(err)
		return
	}

	if hostPortURL.Opaque == "443" { //https访问
		address = hostPortURL.Scheme + ":443"
	} else { //http访问
		if strings.Index(hostPortURL.Host, ":") == -1 { //host不带端口， 默认80
			address = hostPortURL.Host + ":80"
		} else {
			address = hostPortURL.Host
		}
	}

	//获得了请求的host和port，就开始拨号吧
	server, err := net.Dial("tcp", address)
	if err != nil {
		panic(err)
	}
	if method == "CONNECT" {
		fmt.Fprint(conn, "HTTP/1.1 200 Connection established\r\n\r\n")
	} else {
		server.Write(bs[:n])
	}
	//进行转发
	go io.Copy(server, conn)
	io.Copy(conn, server)
}